<template>
  <div class="add-form">
    <van-form>
      <van-field v-model="form.name" :placeholder="$t('component.addGoods.3')" :label="$t('component.addGoods.2')" required :rules="[{ required: true}]"></van-field>
      <van-field :value="typeName" readonly @click="handleCateSelect" :placeholder="$t('component.addGoods.5')" :label="$t('component.addGoods.4')" required :rules="[{ required: true}]"></van-field>
      <span v-for="item in typeParams" :key="item.typeParam.id">
        <van-field v-if="item.typeParam.type=='select'" :label="item.typeParam.portugalName" >
          <template #input >
            <van-dropdown-menu>
              <van-dropdown-item v-model="item.typeParam.value" :options="item.paramValues" />
            </van-dropdown-menu>
          </template>
        </van-field>
        <van-field v-else :label="item.typeParam.portugalName" v-model="item.typeParam.value"/>
      </span>
      <div class="des-p">
        <p>{{ $t("component.addGoods.6") }}</p>
        <quill-editor style="height: 200px" v-model="form.des" ref="myQuillEditor" :options="editorOption"> </quill-editor>
      </div>
      <!-- <van-field type="textarea" maxlength="2000" show-word-limit :rows="6" v-model="form.des" :placeholder="$t('component.addGoods.7')" :label="$t('component.addGoods.6')"></van-field> -->
      <van-field :label="$t('component.addGoods.8')">
        <template #input>
          <van-radio-group v-model="form.dealType" direction="horizontal">
            <van-radio checked-color="#fb8c24" icon-size="16" name="0">{{ $t("component.addGoods.9") }}</van-radio>
            <van-radio checked-color="#fb8c24" icon-size="16" name="1">{{ $t("component.addGoods.10") }}</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <van-field v-if="form.dealType == 0" v-model="form.price" :label="$t('component.addGoods.11')" :placeholder="$t('component.addGoods.11')">
        <template slot="right-icon">kz</template>
      </van-field>
      <van-field :label="$t('component.addGoods.12')">
        <template #input>
          <van-radio-group v-model="form.faceToFace" direction="horizontal">
            <van-radio checked-color="#fb8c24" icon-size="16" name="1">{{ $t("component.addGoods.13") }}</van-radio>
            <van-radio checked-color="#fb8c24" icon-size="16" name="0">{{ $t("component.addGoods.14") }}</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <van-field name="uploader" required :rules="[{ required: true}]">
        <template #input>
           <div style="background: #fff">
            <div class="mb10">
              {{ $t("component.addGoods.15") }}
            </div>
            <van-uploader :max-count="9" multiple :file-list="uploadList" :after-read="multipleUpload" @delete="handleRemove" :preview-full-image="false"/>
          </div>
        </template>
      </van-field>
    
  <!--    <van-field v-model="form.telephone" :placeholder="$t('component.addGoods.17')" :label="$t('component.addGoods.16')"></van-field>-->
  <!--    <van-field v-model="form.email" :placeholder="$t('component.addGoods.19')" :label="$t('component.addGoods.18')"></van-field>-->
      <van-field :value="areaName" readonly @click="handleLocationSelect" :placeholder="$t('component.addGoods.21')" :label="$t('component.addGoods.20')"></van-field>
  <!--    <van-field v-model="form.address" :placeholder="$t('component.addGoods.23')" :label="$t('component.addGoods.22')"></van-field>-->
      <!-- <div class="map-container">
        <div class="map" ref="map" style="width: 100%; height: 300px"></div>
      </div> -->
      <div class="flex m20">
        <van-button native-type="submit" style="border-radius: 4px" block type="primary" color="#fb8c24" @click="handleSubmit">{{ $t("component.addGoods.25") }}</van-button>
      </div>
    </van-form>
  
    <ModalCate v-if="cateShow" :showAll="false" :category-id="categoryId" :section-id="sectionId" @close="cateShow = false" @confirm="handleCateConfirm" />
    <ModalLocation :showAll="false" v-if="locationShow" :p-code="pCode" :c-code="cCode" @close="locationShow = false" @confirm="handleLocationConfirm" />
  </div>
</template>
<script>
import Api from "@/api";
import { Domain, MAPKEY } from "@/constants";
import { isEmail } from "@/utils";
import { Loader } from "@googlemaps/js-api-loader";
import ModalCate from "@/components/modal-cate";
import ModalLocation from "@/components/modal-location";
import { quillEditor } from "vue-quill-editor"; //调用编辑器
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import {Toast} from "vant";
export default {
  name: "AddForm",
  components: { ModalCate, ModalLocation, quillEditor },
  props: {
    goods: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      domain: Domain,
      uploadUrl: Api.uploadUrl,
      map: null,
      cateShow: false,
      locationShow: false,
      categoryId: "",
      categoryName: "",
      sectionId: "",
      sectionName: "",
      pCode: "",
      pName: "",
      cCode: "",
      cName: "",
      form: {
        name: "",
        des: "",
        price: "",
        imgList: "",
        telephone: "",
        email: "",
        address: "",
        faceToFace: "0",
        dealType: "0",
        latitude: "",
        longitude: "",
        areaName: "",
        parameterList: "",
      },
      typeParams: [],
      uploadList: [],
      editorOption: {
        placeholder: this.$t("component.addGoods.7"),
        modules: {
          toolbar: "",
        },
      },
    };
  },
  created() {
    if (this.goods.id) {
      this.form = this.goods;
      this.sectionId = this.goods.sectionId;
      this.sectionName = this.goods.sectionName;
      this.categoryId = this.goods.categoryId;
      this.categoryName = this.goods.categoryName;
      const [pCode = "", cCode = ""] = this.goods.areaCode.split("/");
      const [pName = "", cName = ""] = this.goods.areaName.split("/");
      this.pCode = pCode;
      this.pName = pName;
      this.cCode = cCode;
      this.cName = cName;
      const imgs = JSON.parse(this.goods.imgList);
      this.uploadList = imgs.map((item) => {
        return {
          path: item,
          url: Domain + item,
        };
      });
    } else {
      this.loadUserInfo();
    }
  },
  mounted() {
    this.initMap();
  },
  computed: {
    typeName() {
      if (this.categoryName) {
        return [this.sectionName, this.categoryName].join("/");
      } else {
        return this.sectionName;
      }
    },
    areaName() {
      if (this.cName) {
        return [this.pName, this.cName].join("/");
      } else {
        return this.cName;
      }
    },
  },
  methods: {
    initMap() {
      const mapLoader = new Loader({
        apiKey: MAPKEY,
        version: "weekly",
      });
      mapLoader.load().then(async () => {
        const position = await this.getPosition();
        this.map = new window.google.maps.Map(this.$refs.map, {
          center: position,
          zoom: 8,
        });
        let marker = null;
        this.map.addListener("click", (mapsMouseEvent) => {
          if (marker) {
            marker.setMap(null);
          }
          this.form.latitude = mapsMouseEvent.latLng.lat();
          this.form.longitude = mapsMouseEvent.latLng.lng();
          marker = new window.google.maps.Marker({
            position: mapsMouseEvent.latLng,
            map: this.map,
          });
        });
      });
    },
    getPosition() {
      return new Promise((resolve) => {
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(
            (position) => {
              const { latitude, longitude } = position.coords;
              resolve({
                lat: latitude,
                lng: longitude,
              });
            },
            () => {
              resolve({
                lat: 0,
                lng: 0,
              });
            }
          );
        } else {
          resolve({
            lat: 0,
            lng: 0,
          });
        }
      });
    },
    loadUserInfo() {
      Api.loadUser().then((res) => {
        this.form.email = res.email;
        this.form.telephone = res.mobile;
      });
    },
    handleCateSelect() {
      this.cateShow = true;
    },
    handleCateConfirm(item) {
      this.cateShow = false;
      this.sectionId = item.query.sectionId;
      this.sectionName = item.sectionName;
      this.categoryId = item.query.categoryId;
      this.categoryName = item.categoryName;
      Api.typeParamsList({ typeId: item.query.categoryId }).then((res) => {
        this.typeParams = res.map((item) => {
          const child = item.paramValues ? item.paramValues.map((p) => Object.assign(p, { text: p.showName, value: p.id })) : [];
          return Object.assign(item, { paramValues: child });
        });
      });
    },
    handleLocationSelect() {
      this.locationShow = true;
    },
    handleLocationConfirm(item) {
      this.locationShow = false;
      this.cName = item.cityName;
      this.pName = item.provinceName;
      this.pCode = item.provicenCode;
      this.cCode = item.cityCode;
      console.log(item);
    },
    multipleUpload(file) {
      if (Array.isArray(file)) {
        file.forEach((item) => {
          this.handleAvatarSuccess(item.file);
        });
      } else {
        this.handleAvatarSuccess(file.file);
      }
    },
    handleAvatarSuccess(file) {
      const params = new FormData();
      params.append("file", file);
      Api.uploadMethod(params).then((res) => {
        if (res.path) {
          this.uploadList.push({
            path: res.path,
            url: Domain + res.path,
          });
        }
      });
    },
    handleRemove(file, detail) {
      this.uploadList.splice(detail.index, 1);
    },
    handleSubmit() {
      if(this.uploadList.length == 0||!this.typeName){
        this.$toast.fail('Falta informação necessária')
        return false
      }
      if (this.cCode) {
        this.form.areaCode = [this.pCode, this.cCode].join("/");
        this.form.areaName = [this.pName, this.cName].join("/");
      } else {
        this.form.areaCode = this.pCode;
        this.form.areaName = this.pName;
      }
      if (!this.uploadList || this.uploadList.length==0){
        Toast("Por favor carregue uma imagem")
        return
      }
      this.form.sectionId = this.sectionId;
      this.form.sectionName = this.sectionName;
      this.form.categoryId = this.categoryId;
      this.form.categoryName = this.categoryName;
      if (this.form.price) {
        this.form.price = this.form.price.replace(/,/g, "");
      }
      if (this.typeParams.length > 0) {
        let arr = [];
        this.typeParams.forEach((item, index) => {
          if (item.typeParam.value) {
            let obj = {};
            if (item.typeParam.type == "select") {
              obj.chinaName = item.typeParam.chinaName;
              obj.englishName = item.typeParam.englishName;
              obj.portugalName = item.typeParam.portugalName;
              item.paramValues.forEach((inner, index) => {
                if (item.typeParam.value === inner.id) {
                  obj.chinaNameInner = inner.chinaName;
                  obj.englishNameInner = inner.englishName;
                  obj.portugalNameInner = inner.portugalName;
                  obj.id = inner.id;
                }
              });
            } else {
              obj.chinaName = item.typeParam.chinaName;
              obj.englishName = item.typeParam.englishName;
              obj.portugalName = item.typeParam.portugalName;
              obj.chinaNameInner = item.typeParam.value;
              obj.englishNameInner = item.typeParam.value;
              obj.portugalNameInner = item.typeParam.value;
              obj.id = null;
            }
            arr.push(obj);
          }
        });
        this.form.parameterList = JSON.stringify(arr);
      }
      const params = {
        ...this.form,
        imgList: JSON.stringify(this.uploadList.map((item) => item.path)),
      };
      if (this.form.id) {
        Api.updateGoods(params).then(() => {
          this.$emit("success");
        });
      } else {
        Api.addGoods(params).then(() => {
          this.$emit("success");
        });
      }
    },
  },
};
</script>

<style lang="less" scoped>
.add-form {
  height: 100%;
}
/deep/ .van-dropdown-menu {
  width: 100%;
  .van-dropdown-menu__bar {
    height: 24px;
    box-shadow: none;
    .van-dropdown-menu__item {
      justify-content: flex-start;
      &::after {
        position: absolute;
        top: 50%;
        right: -4px;
        margin-top: -5px;
        border: 3px solid;
        border-color: transparent transparent #dcdee0 #dcdee0;
        -webkit-transform: rotate(-45deg);
        transform: rotate(-45deg);
        opacity: 0.8;
        content: "";
      }
      .van-dropdown-menu__title::after {
        content: none;
      }
    }
  }
}
.map-container {
  background: #fff;
  box-sizing: border-box;
  padding: 10px;
  .map {
    background: #f2f2f2;
  }
}
.des-p {
  background-color: #fff;
  padding: 0 16px 10px;
  p {
    height: 44px;
    line-height: 44px;
  }
}
</style>
